<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 海鼎账号角色解析工具2
 *
 * @icon fa fa-circle-o
 */
class Hdright extends Backend
{

    /**
     * Hdright模型对象
     * @var \app\admin\model\Hdright
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Hdright;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }







            $result = 1;
    
         


            if($result)
            {
                
            Db::execute('TRUNCATE fa_hdright');   
            $target_json = $params['target_text'];
            // $own_json = $params['own_text'];
            unset($params['target_text']);
            // unset($params['own_text']);
            

            $target_data = json_decode($target_json, true);
            if(!isset($target_data))
            {
                $this->error('对标用户Json格式不正确');
            }

            //初始化插入数组key
            $key=0;
            //先讲目标json存入数据库
            foreach ($target_data as &$item) {
                // 保留需要的键，删除多余的键
                $item = array_intersect_key($item, array_flip(['code', 'name']));
             
                //将待插入数据库的数据赋值到数组
                $insert[$key]['target_code']=$item['code'];
                $insert[$key]['target_name']=$item['name'];
                $insert[$key]['eng']='';

                //判断所属组织，有字母的是SN 9701组织， SH是上海的9671组织
                if($this->is_english($item['code']))
                {

                        if(preg_match('/\d+/',$item['code'],$arr)){
                            $no_code = $arr[0];
                            $en_head = str_replace($arr[0],'',$item['code']);
                         }
                         else
                         {
                            $this->error("英文code解析错误");
                         }



                        $insert[$key]['eng']=$en_head;


 
                      
                }
 


                $key++;
            }

            $this->model->saveAll($insert);




                Db::commit();
            }
            else
            {
                Db::rollback();
                $this->error('系统错误');
            }





            
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }



    //将一维数组，拆分为包含字母和不包含的。
    public function is_english($str) {
        $pattern = '/[a-zA-Z]/';
        return preg_match($pattern, $str);
    }

}
